package sk.vrto.service.dao.hibernate;

import org.hibernate.Query;
import org.hibernate.Session;
import sk.vrto.domain.Email;
import sk.vrto.domain.User;
import sk.vrto.service.dao.EmailRepository;
import sk.vrto.web.ApplicationInjector;

import java.util.Collection;
import java.util.List;

/**
 * EmailRepository that uses SQL database to obtain emails from.
 * Uses Hibernate as an ORM provider.
 */
@SuppressWarnings("unchecked")
public class HibernateEmailRepository implements EmailRepository {

    @Override
    public Collection<Email> loadEmailsForUser(User user) {
        Session session = ApplicationInjector.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            Query query = session.createQuery("from Email e where e.user = :user");
            query.setParameter("user", user);
            List<Email> emails = query.list();
            session.getTransaction().commit();
            return emails;
        } finally {
            session.close();
        }
    }

    @Override
    public Email find(Integer key) {
        Session session = ApplicationInjector.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            Query query = session.createQuery("from Email e where e.id = :id");
            query.setParameter("id", key);
            List<?> result = query.list();
            Email email= result.isEmpty() ? null : (Email) result.get(0);
            session.getTransaction().commit();
            return email;
        } finally {
            session.close();
        }
    }

    @Override
    public Collection<Email> load() {
        Session session = ApplicationInjector.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            Query query = session.createQuery("from Email ");
            List<Email> emails = query.list();
            session.getTransaction().commit();
            return emails;
        } finally {
            session.close();
        }
    }

    @Override
    public void insert(Email email) {
        Session session = ApplicationInjector.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            session.saveOrUpdate(email);
            session.getTransaction().commit();
        } finally {
            session.close();
        }
    }

    @Override
    public void update(Email email) {
        insert(email);
    }

    @Override
    public void delete(Email email) {
        Session session = ApplicationInjector.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            session.delete(email);
            session.getTransaction().commit();
        } finally {
            session.close();
        }
    }

}
